package com.gulimall.order.config;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.annotation.PostConstruct;


@Configuration
public class RabbitConfig {


    RabbitTemplate rabbitTemplate;

    //
//    public RabbitConfig(RabbitTemplate rabbitTemplate) {
//        this.rabbitTemplate = rabbitTemplate;
//        recieveMessage();
//    }

    @Primary
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setMessageConverter(messageContext());
        recieveMessage();
        return rabbitTemplate;
    }

    @Bean
    public MessageConverter messageContext() {

        return new Jackson2JsonMessageConverter();
    }


    public void recieveMessage() {

        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *
             * @param correlationData
             * @param b
             * @param s
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                /**
                 * 防止消息丢失
                 *  做好消息确认机智 (pulisher ,cousumer [手动ack机智])
                 *  每一个发送的消息都在数据库最好纪录, 定期将失败的消息 在发送一次
                 */
                System.out.println("confirm" + correlationData + "====>b----" + b + "-------> s---" + s);
            }
        });

        //开启发送端消息抵达队列的确认回掉
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             *  只要信息没有投递给指定队列,就触发这个回调
             * @param message       投递失败的信息详细信息
             * @param i 回复的状态码
             * @param s 回复的文本内容
             * @param s1    当时这个信息发给那个交换机
             * @param s2    这个信息发给那个路邮件
             */
            @Override
            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
                System.out.println("message" + message + "--->" + i + "=====>" + s + "----" + s1 + "------" + s2);
            }
        });
    }
}
